package core.util;

import java.io.File;
import java.io.FileFilter;

/**
 * @author songduk park
 * 
 */
public class DeleteOldFiles {

	long days = 0;
	File dir = null;
	long now = System.currentTimeMillis();

	public DeleteOldFiles(int days, File direcotry) {
		this.days = 86400000 * days;
		this.dir = direcotry;
	}

	public int delete() {
		if (days <= 0)
			return 0;

		int deleted = 0;

		File[] oldFiles = dir.listFiles(new FileFilter() {

			@Override
			public boolean accept(File pathname) {
				if (pathname.isDirectory())
					return false;

				long lastModified = pathname.lastModified();
				long elapse = now - lastModified;
				// System.out.println(elapse + " , " + pathname.getName());

				if (elapse >= days)
					return true;
				else
					return false;
			}
		});

		for (int i = 0; i < oldFiles.length; i++) {
			File file = oldFiles[i];
			System.out.println("old file = " + file);

			try {
				file.delete();
				++deleted;
			} catch (Exception e) {
				System.out.println("can't delete file :" + file);
			}
		}

		return deleted;
	}
}
